package com.cube.truthseer.common.security.context;



import com.cube.truthseer.common.cache.Cache;
import com.cube.truthseer.common.security.AuthUser;
import com.cube.truthseer.common.security.enums.SecurityEnum;
import com.cube.truthseer.common.security.token.SecretKeyUtil;
import com.cube.truthseer.common.utils.RedisKeyUtil;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 用户上下文
 */
@Component
public class UserContext {

    @Resource
    private Cache cache;

    /**
     * 根据request获取当前登录用户信息，如果没有登录则返回null
     *
     * @return 授权用户
     */

    public AuthUser getLoginUser() {
        String accessToken = getCurrentUserToken();
        AuthUser authUser = getAuthUser(accessToken);
        String uuid = UserContext.getCurrentUserUUID();
        if(authUser==null)return null;
        String loginKey = RedisKeyUtil.loginKey(authUser);
        String cache_uuid = (String) this.cache.get(loginKey);
        //用户未登录
        if (uuid == null || cache_uuid == null) return null;
        //用户账号被挤掉了
        if (!uuid.equals(cache_uuid)) return null;
        return authUser;
    }

    private static String getCurrentUserToken() {
        if (RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getHeader(SecurityEnum.HEADER_TOKEN.getValue());
        }
        return null;
    }

    public static String getCurrentUserUUID() {
        if (RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getHeader(SecurityEnum.UUID.getValue());
        }
        return null;
    }

    /**
     * 根据jwt获取token重的用户信息
     *
     * @param accessToken token
     * @return 授权用户
     */
    private static AuthUser getAuthUser(String accessToken) {
        try {
            //解密出token里的claims
            Claims claims
                    = Jwts.parser()
                    .setSigningKey(SecretKeyUtil.generalKeyByDecoders())
                    .parseClaimsJws(accessToken).getBody();
            //获取存储在claims中的用户信息
            String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();
            return new Gson().fromJson(json, AuthUser.class);
        } catch (Exception e) {
//            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
            return null;
        }
    }
}
